'use strict';

var path = require('path'),
    passport = require('passport'),
    passportJWT = require('passport-jwt'),
    rs = require('jsrsasign'),
    rsu = require('jsrsasign-util'),
    db = require('../bookshelf/bookshelf.config'),
    User = require('../bookshelf/models/user.model');

var cert = rsu.readFile(path.join(__dirname, process.env.publicCert));
var pem = rsu.readFile(path.join(__dirname, process.env.privateKey));
var prv = rs.KEYUTIL.getKey(pem, process.env.privatePwd);


function createToken(sPayLoad) {
    var sHeader = {'alg': 'RS256', 'typ': 'JWT'};

/*
    sPayLoad.exp = ~~(new Date().getTime() / 1000) + (parseInt(process.env.tokenExpiration));
    sPayLoad.iat = ~~(new Date().getTime() / 1000 - 60);
*/
    sPayLoad.exp = (new Date().getTime() / 1000) + (parseInt(process.env.tokenExpiration));
    sPayLoad.iat = (new Date().getTime() / 1000 - 60);

    return rs.jws.JWS.sign(
        null, JSON.stringify(sHeader), JSON.stringify(sPayLoad),
        prv, process.env.privatePwd);
}

function verifyToken(sToken) {
    return rs.jws.JWS.verify(sToken, cert);
}

module.exports = function (app) {
    app.use(passport.initialize());
    var JwtStrategy = passportJWT.Strategy;
    var ExtractJwt = passportJWT.ExtractJwt;

    var opts = {
        jwtFromRequest: ExtractJwt.fromAuthHeader(),
        secretOrKey: cert.toString(),
        ignoreExpiration: true,
        algorithms: ['RS256'],
        passReqToCallback: true
    };

    passport.use(new JwtStrategy(opts, function (req, jwtPayload, done) {
        User.where('user_id', jwtPayload.id).fetch().then(function (user) {
            if (user) {
                done(null, user);
            } else {
                done(null, false);
            }
        }).catch(function (err) {
            console.error(err);
            return done(err, false);
        });
    }));

    return {
        createToken: createToken,
        verifyToken: verifyToken,
        passport: passport
    };
};